<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-09-03 14:59
 *
 * 项目：rm  -  $  - ${FILE_NAME}
 *
 * 作者：liwei 
 */


namespace modules\levbdu\table;

use Lev;
use lev\base\Modelv;
use modules\levbdu\helpers\levbduSetHelper;

!defined('INLEV') && exit('Access Denied LEV');

class BaseLevbdu extends Modelv
{

    public static function tableName($tableName = '{{%levbdu}}', $prefix = true)
    {
        return parent::tableName($tableName ?: '{{%levbdu}}', $prefix); // TODO: Change the autogenerated stub
    }

    public static function bdInfo($uid, $field = '*') {
        return static::findOne("(uid=$uid OR bduid=$uid) AND status=0", $field);
    }

    public static function myBdus($uid, $limit = 20, $load = true) {
        $bdInfo = static::bdInfo($uid);
        $lists = [];
        if ($bdInfo) {
            $where = ['uid'=>$bdInfo['uid'], 'status'=>0];
            $lists = $load ? static::pages($where, $limit) : static::pageButtons($where, $limit);
        }
        return $lists;
    }


    public static function SaveBdu($bdid, $bduid) {
        if (bduHelper::bdInfo(Lev::$app['uid'])) {
            bduHelper::delete(['id'=>$bdid]);
            return Lev::responseMsg(-2002, '账号已绑定');
        }

        $bdInfo = bduHelper::bdInfo($bduid);
        $uid = $bdInfo ? $bdInfo['uid'] : $bduid;
        if ($uid == Lev::$app['uid']) {
            bduHelper::delete(['id'=>$bdid]);
            return Lev::responseMsg(-2003, '账号相同');
        }
        bduHelper::update(['uid'=>$uid, 'bduid'=>Lev::$app['uid'], 'status'=>0, 'uptime'=>Lev::$app['timestamp']], ['id'=>$bdid]);
        if (!bduHelper::findOne(['uid'=>$uid, 'bduid'=>$uid])) {
            bduHelper::insert(['uid'=>$uid, 'bduid'=>$uid, 'status'=>0, 'uptime'=>Lev::$app['timestamp'], 'addtime'=>Lev::$app['timestamp']]);
        }

        return Lev::responseMsg();
    }
}